Page({
  data: {
    statusBarHeight: 32,
    backgroundImage: '../../images/cloud.jpg',
    backgroundColor: '#62aadc',
    current: {
      temp: '0',
      weather: '数据获取中',
      humidity: '1',
      icon: 'xiaolian'
    },
    today: {
      temp: 'N/A',
      weather: '暂无'
    },
    tomorrow: {
      temp: 'N/A',
      weather: '暂无'
    },
    hourlyData: [],
    weeklyData: [],
    city: '广州',
    lon: 113.27,
    lat: 23.13,
    address: '广州',
    width: 375,
    scale: 1,
  },

  goDiary() {
    try {
      var url = '/pages/diary/index';
      wx.navigateTo({
        url: url
      });
    } catch (e) {
      console.log(e);
    }
  },

  onShareAppMessage: function onShareAppMessage() {
    if (!isUpdate) {
      return {
        title: '我发现一个好玩的天气小程序，分享给你看看！',
        path: '/pages/weather/index'
      };
    } else {
      var { lat, lon, address, province, city, county } = this.data
      var url = '/pages/weather/index?lat=' + lat + '&lon=' + lon + '&address=' + address + '&province=' + province + '&city=' + city + '&county=' + county;
      return {
        title: '\u300C' + address + '\u300D\u73B0\u5728\u5929\u6C14\u60C5\u51B5\uFF0C\u5FEB\u6253\u5F00\u770B\u770B\u5427\uFF01',
        path: url
      };
    }
  },

  onPullDownRefresh() {
    this.getWeatherData(function () {
      wx.stopPullDownRefresh();
    });
  },

  onLoad() {
    let that = this
    this.getWeatherData()
    wx.getSystemInfo({
      success(res) {
        var width = res.windowWidth;
        var scale = width / 375;
        // console.log(scale * res.statusBarHeight*2+24)
        that.setData({
          width: width,
          scale: scale,
          paddingTop: res.statusBarHeight + 12
        });
      }
    });

    var pages = getCurrentPages(); //获取加载的页面
    var currentPage = pages[pages.length - 1]; //获取当前页面的对象
    var query = currentPage.options;
    if (query && query.address && query.lat && query.lon) {
      var province = query.province,
        city = query.city,
        county = query.county,
        address = query.address,
        lat = query.lat,
        lon = query.lon;

      this.setData({
        city: city,
        province: province,
        county: county,
        address: address,
        lat: lat,
        lon: lon
      }, function () {
        _this6.getWeatherData();
      });
    } else {
      let that = this
      // 获取缓存数据
      this.setDataFromCache();

      wx.getLocation({
        type: 'gcj02',
        success: that.updateLocation,
        fail(e) {
          wx.showToast({
            title: '检测到您未授权使用位置权限，请先开启哦',
            icon: 'none',
            duration: 3000
          })
        }
      })
    }
  },



  setDataFromCache() {
    let that = this;
    wx.getStorage({
      key: 'defaultData',
      success: function success(_ref2) {
        var data = _ref2.data;

        if (data && !isUpdate) {
          // 存在并且没有获取数据成功，那么可以给首屏赋值上次数据
          var { current, backgroundColor, backgroundImage, today, tomorrow, address, tips, hourlyData } = data

          that.setData({
            current,
            backgroundColor,
            backgroundImage,
            today,
            tomorrow,
            address,
            tips,
            hourlyData
          });
        }
      }
    });
  },

  chooseLocation() {
    // 地图选择位置控件，箭头函数绑定 this, 但是在 wx.* 等api中由于是闭包, this 指向的是 wx api 的对象而不是组件
    let that = this
    wx.chooseLocation({
      success(res) {
        let { longitude, latitude, name, address } = res
        let { lon, lat } = that.data
        // 判断经纬度有没有变化 
        if (longitude === lon && latitude === lat) {
          that.getWeatherData()
        } else {
          that.updateLocation(res);
        }
      }
    })
  },

  render(res) {
    let { current, daily, lifeStyle, oneWord, effect } = res
    let { backgroundColor, backgroundImage } = current
    let backgroundImageUrl = `../../images/bg/${backgroundImage}`

    var _today = daily[0],
      _tomorrow = daily[1];
    var today = {
      temp: _today.minTemp + '/' + _today.maxTemp + '\xB0',
      icon: _today.dayIcon,
      weather: _today.day
    };
    var tomorrow = {
      temp: _tomorrow.minTemp + '/' + _tomorrow.maxTemp + '\xB0',
      icon: _tomorrow.dayIcon,
      weather: _tomorrow.day
      // daily.forEach((v) => {
      //   v.time = v.time + 24 * 60 * 60 * 1000
      // })
      // console.log(hourly)
    }
    this.setData({
      current,
      oneWord,
      lifeStyle,
      backgroundColor,
      backgroundImage: backgroundImageUrl,
      weeklyData: daily,
      today,
      tomorrow
    });

    // 缓存数据
    this.dataCache();
  },

  dataCache: function dataCache() {
    var { current, backgroundColor, backgroundImage, today, tomorrow, address, tips, hourlyData } = this.data

    wx.setStorage({
      key: 'defaultData',
      data: {
        current,
        backgroundColor,
        backgroundImage,
        todaytoday,
        tomorrow,
        address,
        tips,
        hourlyData
      }
    });
  },

  getWeatherData() {
    let that = this
    // wx.showLoading 和 wx.showToast 同时只能显示一个
    /* wx.showLoading({
      title: '获取数据中',
      mask: true
    }) */

    let { county, province, city, lon, lat } = that.data
    // 获取天气
    wx.cloud.callFunction({
      name: 'he-weather',
      data: { lon, lat },
    }).then(res => {
      that.render(res.result)
    }).catch(e => {
    })

    // 获取空气质量
    wx.cloud.callFunction({
      name: 'he-air',
      data: { city },
    }).then(res => {
      that.setData({
        air: res.result
      });
    }).catch(e => {
    })

    wx.request({
      url: 'https://wis.qq.com/weather/common',
      data: {
        source: 'wxa',
        weather_type: 'tips',
        province: province,
        city: city,
        county: county
      },
      success(res) {
        var result = (res.data || {}).data;
        if (result && result.tips) {
          var tips = result.tips.observe;
          if (!tips) return
          var index = Math.floor(Math.random() * Object.keys(tips).length);
          tips = tips[index];
          that.setData({ tips: tips })
        }
      },
    })
  },

  updateLocation(res) {
    let { longitude, latitude, name } = res
    let data = {
      lat: latitude,
      lon: longitude
    };
    if (name) {
      data.address = name;
    }
    this.setData(data);
    this.getAddress(longitude, latitude, name);
  },
  // 处理逆经纬度
  getAddress(lon, lat, name) {
    let that = this
    wx.showLoading({
      title: '定位中',
      mask: true
    });

    let fail = e => {
      that.setData({
        address: name || '广州'
      })
      wx.hideLoading();
      that.getWeatherData();
    }
    return wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      data: {
        location: lat + ',' + lon,
        key: 'XUYBZ-AHYHR-Q7JWC-W2VGL-EA656-KTF2E',
        get_poi: 0
      },
      success(res) {
        let { statusCode, data: { result } } = res
        if (statusCode === 200 && result && result.address) {
          let { address, formatted_addresses, address_component } = result

          if (formatted_addresses && (formatted_addresses.recommend || formatted_addresses.rough)) {
            address = formatted_addresses.recommend || formatted_addresses.rough;
          }
          let province = address_component.province,
            city = address_component.city,
            county = address_component.district;

          that.setData({
            province: province,
            county: county,
            city: city,
            address: name || address
          });
          that.getWeatherData();
          wx.hideLoading()
        } else {
          //失败
          fail();
          wx.hideLoading()
        }
      },
      fail: fail
    });
  }
})